/**
 * Copyright 2010 VTT Finnish Technical Research Centre
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.osami.syncagent.server.tcpip;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.osami.syncagent.server.SyncAgentServer;

/**
 * Listen broadcast messages. When new server comes on-line. It will send a broadcast 
 * message to local network about it's presence. This class calls SyncAgentServer with 
 * the message and either adds or removes client from list.
 * 
 * @author elekko
 *
 */
public class SyncAgentBroadCastClient implements Runnable {
	private DatagramSocket socket;
	private SyncAgentServer serverRef;
	public boolean stopThread;
	
	public SyncAgentBroadCastClient(String bcAddress, SyncAgentServerTCPIP serv) {
		stopThread = false;
		serverRef =serv;
		InetAddress address;
		System.out.println("SyncAgentBroadCastClient bcAdress " + bcAddress);
		try {
			socket = new DatagramSocket(serv.BC_PORT);
			address = InetAddress.getByName(bcAddress);
			socket.setBroadcast(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendPacket(DatagramPacket packet) throws IOException
	{
		socket.send(packet);
		
	}
	
	@Override
	public void run() {
		DatagramPacket packet;
	    
        // get a few quotes
		while (!stopThread) {

			byte[] buf = new byte[256];
			packet = new DatagramPacket(buf, buf.length);
			try {
				socket.receive(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String received = new String(packet.getData(), 0, packet.getLength());
			serverRef.interpretMessage(received);
			System.out.println("Broadcast message: " + received);
		}
		socket.close();
	}

}
